package com.manor.im.helper;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.manor.common.CommonAppConfig;
import com.manor.common.CommonAppContext;
import com.manor.common.Constants;
import com.manor.common.bean.ChatInfoBean;
import com.manor.common.bean.CustomTipBean;
import com.manor.common.utils.GiftTextRender;
import com.manor.common.utils.Gson2Util;
import com.manor.common.utils.KLog;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.StaIntentUtil;
import com.manor.common.utils.StringUtil;
import com.manor.im.R;
import com.manor.im.bean.SendGiftBean;
import com.manor.im.bean.TreasureBean;
import com.manor.im.utils.ChatLiveImUtil;
import com.tencent.imsdk.v2.V2TIMCustomElem;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.qcloud.tim.uikit.modules.chat.ChatLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.input.InputLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.message.MessageLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.message.holder.ICustomMessageViewGroup;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.message.holder.IOnCustomMessageDrawListener;
import com.tencent.qcloud.tim.uikit.modules.message.ChatUtilInfo;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;

import org.json.JSONObject;

import androidx.annotation.LayoutRes;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;

public class ChatLayoutHelper {

    private static final String TAG = ChatLayoutHelper.class.getSimpleName();

    private Context mContext;

    public ChatLayoutHelper(Context context) {
        mContext = context;
    }

    public void customizeChatLayout(final ChatLayout layout) {
        customizeChatLayout(layout,false);
    }


    public void customizeChatLayout(final ChatLayout layout,final boolean isGroup) {

//        //====== NoticeLayout使用范例 ======//
//        NoticeLayout noticeLayout = layout.getNoticeLayout();
//        noticeLayout.alwaysShow(true);
//        noticeLayout.getContent().setText("现在插播一条广告");
//        noticeLayout.getContentExtra().setText("参看有奖");
//        noticeLayout.setOnNoticeClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ToastUtil.toastShortMessage("赏白银五千两");
//            }
//        });
//
        //====== MessageLayout使用范例 ======//
        MessageLayout messageLayout = layout.getMessageLayout();
//        ////// 设置聊天背景 //////
        messageLayout.setBackground(new ColorDrawable(0xFFF8F8F8));
//        ////// 设置头像 //////
//        // 设置默认头像，默认与朋友与自己的头像相同
//        messageLayout.setAvatar(R.drawable.ic_more_file);
//        // 设置头像圆角
//        messageLayout.setAvatarRadius(50);
//        // 设置头像大小
//        messageLayout.setAvatarSize(new int[]{48, 48});
//
//        ////// 设置昵称样式（对方与自己的样式保持一致）//////
//        messageLayout.setNameFontSize(12);
//        messageLayout.setNameFontColor(0xFF8B5A2B);
//
        ////// 设置气泡 ///////
        // 设置自己聊天气泡的背景
        messageLayout.setRightBubble(ResourcesCompat.getDrawable(CommonAppContext.sInstance.getResources(),
                R.drawable.chat_bg_right, null));
        // 设置朋友聊天气泡的背景
        messageLayout.setLeftBubble(ResourcesCompat.getDrawable(CommonAppContext.sInstance.getResources(),
                R.drawable.chat_bg_left, null));
//
//        ////// 设置聊天内容 //////
//        // 设置聊天内容字体字体大小，朋友和自己用一种字体大小
//        messageLayout.setChatContextFontSize(15);
        // 设置自己聊天内容字体颜色
        messageLayout.setRightChatContentFontColor(0xFFFFFFFF);
        // 设置朋友聊天内容字体颜色
        messageLayout.setLeftChatContentFontColor(0xFFFFFFFF);
//
//        ////// 设置聊天时间 //////
//        // 设置聊天时间线的背景
//        messageLayout.setChatTimeBubble(new ColorDrawable(0xFFE4E7EB));
//        // 设置聊天时间的字体大小
//        messageLayout.setChatTimeFontSize(12);
//        // 设置聊天时间的字体颜色
//        messageLayout.setChatTimeFontColor(0xFF7E848C);
//
//        ////// 设置聊天的提示信息 //////
//        // 设置提示的背景
//        messageLayout.setTipsMessageBubble(new ColorDrawable(0xFFE4E7EB));
//        // 设置提示的字体大小
//        messageLayout.setTipsMessageFontSize(12);
//        // 设置提示的字体颜色
//        messageLayout.setTipsMessageFontColor(0xFF7E848C);
//

        // 设置自定义的消息渲染时的回调
        messageLayout.setOnCustomMessageDrawListener(new CustomMessageDraw());


//        // 新增一个PopMenuAction
//        PopMenuAction action = new PopMenuAction();
//        action.setActionName("test");
//        action.setActionClickListener(new PopActionClickListener() {
//            @Override
//            public void onActionClick(int position, Object data) {
//                ToastUtil.toastShortMessage("新增一个pop action");
//            }
//        });
//        messageLayout.addPopAction(action);
//
//        final MessageLayout.OnItemClickListener l = messageLayout.getOnItemClickListener();
//        messageLayout.setOnItemClickListener(new MessageLayout.OnItemClickListener() {
//            @Override
//            public void onMessageLongClick(View view, int position, MessageInfo messageInfo) {
//                l.onMessageLongClick(view, position, messageInfo);
//                ToastUtil.toastShortMessage("demo中自定义长按item");
//            }
//
//            @Override
//            public void onUserIconClick(View view, int position, MessageInfo messageInfo) {
//                l.onUserIconClick(view, position, messageInfo);
//                ToastUtil.toastShortMessage("demo中自定义点击头像");
//            }
//        });


        //====== InputLayout使用范例 ======//
        InputLayout inputLayout = layout.getInputLayout();

        inputLayout.setBackgroundColor(Color.WHITE);

//        //  隐藏音频输入的入口，可以打开下面代码测试
        inputLayout.disableAudioInput(true);
//        //  隐藏表情输入的入口，可以打开下面代码测试
//        inputLayout.disableEmojiInput(true);
//        //  隐藏更多功能的入口，可以打开下面代码测试
//        inputLayout.disableMoreInput(true);
//        //  可以用自定义的事件来替换更多功能的入口，可以打开下面代码测试
//        inputLayout.replaceMoreInput(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ToastUtil.toastShortMessage("自定义的更多功能按钮事件");
//                MessageInfo info = MessageInfoUtil.buildTextMessage("自定义的消息");
//                layout.sendMessage(info, false);
//            }
//        });
//        //  可以用自定义的fragment来替换更多功能，可以打开下面代码测试
//        inputLayout.replaceMoreInput(new CustomInputFragment().setChatLayout(layout));
//
//        //  可以disable更多面板上的各个功能，可以打开下面代码测试
        inputLayout.disableCaptureAction(false);
        inputLayout.disableSendFileAction(false);
        inputLayout.disableGiftAction(true);
        inputLayout.disableSendPhotoAction(false);
        inputLayout.disableVideoRecordAction(false);
//        if (!isGroup) {
//            inputLayout.enableAudioCall();
//            inputLayout.enableVideoCall();
//        }
        //  可以自己增加一些功能，可以打开下面代码测试
        // 增加一个欢迎提示富文本
//        InputMoreActionUnit unit = new InputMoreActionUnit();
//        unit.setIconResId(R.drawable.custom);
//        unit.setTitleId(R.string.test_custom_action);
//        unit.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Gson gson = new Gson();
//                CustomHelloMessage customHelloMessage = new CustomHelloMessage();
//                customHelloMessage.version = TUIKitConstants.version;
//                customHelloMessage.text = "欢迎加入云通信IM大家庭！";
//                customHelloMessage.link = "https://cloud.tencent.com/document/product/269/3794";
//                String data = gson.toJson(customHelloMessage);
//                MessageInfo info = MessageInfoUtil.buildCustomMessage(data);
//                layout.sendMessage(info, false);
//            }
//        });
//        inputLayout.addAction(unit);
    }

//    public static class CustomInputFragment extends BaseInputFragment {
//        @Nullable
//        @Override
//        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
//            View baseView = inflater.inflate(R.layout.test_chat_input_custom_fragment, container, false);
//            Button btn1 = baseView.findViewById(R.id.test_send_message_btn1);
//            btn1.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    ToastUtil.toastShortMessage("自定义的按钮1");
//                    if (getChatLayout() != null) {
//                        Gson gson = new Gson();
//                        CustomHelloMessage customHelloMessage = new CustomHelloMessage();
//                        String data = gson.toJson(customHelloMessage);
//                        MessageInfo info = MessageInfoUtil.buildCustomMessage(data);
//                        getChatLayout().sendMessage(info, false);
//                    }
//                }
//            });
//            Button btn2 = baseView.findViewById(R.id.test_send_message_btn2);
//            btn2.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    ToastUtil.toastShortMessage("自定义的按钮2");
//                    if (getChatLayout() != null) {
//                        Gson gson = new Gson();
//                        CustomHelloMessage customHelloMessage = new CustomHelloMessage();
//                        String data = gson.toJson(customHelloMessage);
//                        MessageInfo info = MessageInfoUtil.buildCustomMessage(data);
//                        getChatLayout().sendMessage(info, false);
//                    }
//                }
//            });
//            return baseView;
//        }
//
//    }

//    public class CustomMessageDraw implements IOnCustomMessageDrawListener {
//
//        /**
//         * 自定义消息渲染时，会调用该方法，本方法实现了自定义消息的创建，以及交互逻辑
//         *
//         * @param parent 自定义消息显示的父View，需要把创建的自定义消息view添加到parent里
//         * @param info   消息的具体信息
//         */
//        @Override
//        public void onDraw(ICustomMessageViewGroup parent, MessageInfo info) {
//            // 获取到自定义消息的json数据
//            if (info.getTimMessage().getElemType() != V2TIMMessage.V2TIM_ELEM_TYPE_CUSTOM) {
//                return;
//            }
//            V2TIMCustomElem elem = info.getTimMessage().getCustomElem();
//            // 自定义的json数据，需要解析成bean实例
//            CustomHelloMessage data = null;
//            try {
//                data = new Gson().fromJson(new String(elem.getData()), CustomHelloMessage.class);
//            } catch (Exception e) {
//                DemoLog.w(TAG, "invalid json: " + new String(elem.getData()) + " " + e.getMessage());
//            }
//            if (data == null) {
//                DemoLog.e(TAG, "No Custom Data: " + new String(elem.getData()));
//            } else if (data.version == TUIKitConstants.JSON_VERSION_1
//                    || (data.version == TUIKitConstants.JSON_VERSION_4 && data.businessID.equals("text_link"))) {
//                CustomHelloTIMUIController.onDraw(parent, data);
//            } else {
//                DemoLog.w(TAG, "unsupported version: " + data.version);
//            }
//        }M
//    }


    public class CustomMessageDraw implements IOnCustomMessageDrawListener {

        @Override
        public void onDraw(ICustomMessageViewGroup parent, MessageInfo info) {
            //KLog.i("CustomMessageDraw--MessageInfo", info);
            if (info.getTimMessage().getElemType() != V2TIMMessage.V2TIM_ELEM_TYPE_CUSTOM) {
                return;
            }
            V2TIMCustomElem elem = info.getTimMessage().getCustomElem();
            KLog.i("CustomMessageDraw--V2TIMCustomElem", elem);
//            JSONObject obj = JSON.parseObject(new String(elem.getData()));


            try {
                View view = null;

                String customMsgData = new String(elem.getData());
                //KLog.i("customMsgData", customMsgData);



                JSONObject obj = new JSONObject(customMsgData);
                String method = obj.getString(ChatLiveImUtil.METHOD);

                if (ChatLiveImUtil.IM_TREASURE.equals(method)) {
                    TreasureBean bean = Gson2Util.fromJson(customMsgData, TreasureBean.class);
                    view = doInflate(R.layout.custom_msg_treasure);
                    parent.addMessageContentView(view);
                    setCustomTreasureView(view, bean);
                } else if (ChatLiveImUtil.GIFT_CUSTOM_TIP.equals(method)) {
                    CustomTipBean bean = Gson2Util.fromJson(customMsgData, CustomTipBean.class);
                    view = doInflate(R.layout.item_chat_custom_tip);
                    parent.addMessageItemView(view);
                    setCustomTipView(view, bean);
                } else if (ChatLiveImUtil.IM_GIFT.equals(method)) {
                    SendGiftBean bean = Gson2Util.fromJson(customMsgData, SendGiftBean.class);
                    if (StringUtil.isNotEmpty(bean.getGroupId()) && !bean.getGroupId().equals("0")){
                        if (bean.getUid().equals(CommonAppConfig.getInstance().getUid())){
                            view = doInflate(R.layout.item_chat_group_gift_right);
                        }else {
                            view = doInflate(R.layout.item_chat_group_gift_left);
                        }

                        setCustomGroupGiftView(view, bean);
                    }else {
                        view = doInflate(R.layout.item_chat_custom_gift);
                    }

                    parent.addMessageContentView(view, false);
                    setCustomGiftView(view, bean);
                }else if (ChatLiveImUtil.IM_CHAT_CALL.equals(method)) {
                    //KLog.i("ChatLiveImUtil.IM_CHAT_CALL.eq",customMsgData);
                    ChatInfoBean bean =  Gson2Util.fromJson(customMsgData, ChatInfoBean.class);
                    if (info.isSelf()){
                        view = doInflate(R.layout.item_chat_im_right);
                    }else {
                        view = doInflate(R.layout.item_chat_im_left);
                    }
                    parent.addMessageContentView(view);
                    setCustomChatView(view, bean, info);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

        private View doInflate(@LayoutRes int layout){
            return  LayoutInflater.from(CommonAppContext.sInstance).inflate(layout, null, false);
        }

        private void setCustomTreasureView(View view, TreasureBean bean) {
            TextView text = view.findViewById(R.id.text);
            text.setText(bean.getContent());
            LinearLayout llLay = view.findViewById(R.id.llContent);
            llLay.setClickable(true);
            llLay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RouteUtil.forwardPath(RouteUtil.PC_WEB, StaIntentUtil.TASK_CENTER);
                }
            });
        }

        private void setCustomTipView(View view, CustomTipBean bean) {
            KLog.e("CICustomMessageViewGroup", bean.isHtml());
            TextView text = view.findViewById(R.id.tv_tip_text);
            text.setText(bean.isHtml() ? Html.fromHtml(TUIKitConstants.covert2HTMLString(bean.getContent())) : bean.getContent());
        }

        private void setCustomGiftView(View view, SendGiftBean bean) {
            ImageView mGiftIcon = view.findViewById(R.id.gift_icon);
            TextView mGiftName = view.findViewById(R.id.gift_name);
            TextView mGiftCount = view.findViewById(R.id.gift_count);
            Glide.with(CommonAppContext.sInstance)
                    .load(bean.getGifticon())
                    .skipMemoryCache(true)
                    .into(mGiftIcon);
            mGiftName.setText(bean.getGiftname());
            mGiftCount.setText(GiftTextRender.renderGiftCount2(bean.getGiftcount()));

        }

        private void setCustomGroupGiftView(View view, SendGiftBean bean) {
            ImageView mGiftIcon = view.findViewById(R.id.ivImage);
            TextView mGiftName = view.findViewById(R.id.tvContent);
            Glide.with(CommonAppContext.sInstance)
                    .load(bean.getGifticon())
                    .skipMemoryCache(true)
                    .into(mGiftIcon);
            String str = "送你"+bean.getGiftcount()+"个"+bean.getGiftname()+"\n@"+bean.getToNickName();
            mGiftName.setText(str);

        }

       //text   icon
       private void setCustomChatView(View view, ChatInfoBean bean, MessageInfo info) {
           ImageView mIvIcon = view.findViewById(R.id.icon);
           TextView mTvName = view.findViewById(R.id.text);

           if (bean.getType() == Constants.CHAT_TYPE_VIDEO) {
               if (info.isSelf()) {
                   mIvIcon.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_chat_video_1));
               } else {
                   mIvIcon.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_chat_video_2));
               }
           } else {
               if (info.isSelf()) {
                   mIvIcon.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_chat_voice_1));
               } else {
                   mIvIcon.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_chat_voice_2));
               }
           }

          String  content = info.isSelf() ? "[发起通话]" : "[对方发起通话]";;

           byte action = bean.getAction();
           if (action == ChatUtilInfo.ACTION_AUD_CANCEL || action == ChatUtilInfo.ACTION_ANC_CANCEL) {
               content = info.isSelf() ? "已取消" : "对方已取消";
           } else if (action == ChatUtilInfo.ACTION_ANC_REFUSE || action == ChatUtilInfo.ACTION_AUD_REFUSE) {
               content = info.isSelf() ? "已拒绝" : "对方已拒绝";
           } else if (action == ChatUtilInfo.ACTION_ANC_HANG_UP || action == ChatUtilInfo.ACTION_AUD_HANG_UP){
               content = bean.getContent();
           }


           mTvName.setText(content);

       }




    }


}
